<script lang="ts" setup>
//作品设置
import { ref, computed, inject, onMounted } from 'vue';
import { useRouter, useRoute } from 'vue-router'
const axios = inject('axios') //注入 axios
// 获取路由信息
const route = useRoute();
// 创建路由对象，用于编程式导航
const router = useRouter()
// 定义后端 图片API 接口路径
// const imageBasePath = 'http://localhost:8080/api/images/';
const imageBasePath = ref('../images/竹简文字背景.png')
// 获取完整的图片 URL
// const getImageUrl = (fileName) => {
//     console.log("imageURL:" + imageBasePath + fileName)
//     return fileName ? `${imageBasePath}${fileName}` : '0 (3).jpg'; // 默认图片处理
// };


const work = ref({
  wname: '', //剧本名称
  typeID: '',  //类型
  workWstate: '',  //剧本审核状态
  copyright: '', //版权登记号
  record: '',  //备案号
  wimage: '',  //封面名称
  money: '',   //作者意愿（金额）
  introduction: '',  //剧本简介
  script_state: '',  //剧本状态（上架/下架）；0:上架、1：下架
  zid: '',           //征稿公告id ZID
  screenwriterBio: ''//编剧简介

}); // 示例数据
// 获取剧本信息
const fetchBookInfo = async (id) => {
  const WID = id;
  console.log("获取到的剧本id：" + JSON.stringify(WID, null, 2));
  try {
    const response = await axios.get(`http://localhost:8080/api/getwork/${WID}`); // 替换为实际的API端点
    work.value = response.data; // 假设后端返回的对象结构与book对象一致
    console.log("获取剧本信息成功：" + JSON.stringify(work.value, null, 2));
    //获取封面
    // 仅在用户上传新头像后更新 
    console.log("work.value.wimage：" + work.value.wimage)
    if (work.value.wimage) {
      work.wimage = work.value.wimage; // 保留用户头像的值
      imageBasePath.value = 'http://localhost:8080/api/images/' + work.value.wimage;
    }
    
  } catch (error) {
    console.error('Error fetching book info:', error);
  }
};

// //获取剧本题材列表
const scriptTypes = ref([]);  // 用于存储从后端获取的题材
const fetchScriptTypes = async (wid) => {
  try {
    const response = await axios.get(`http://localhost:8080/api/getworklabelByWid/${wid}`);
    scriptTypes.value = response.data.data; // 更新题材数据
    console.log('获取题材列表成功：', JSON.stringify(scriptTypes.value, null, 2));
    console.log('获取题材列表成功：', JSON.stringify(scriptTypes[0].value.bname, null, 2));
  } catch (error) {
    console.error('Error fetching script types:', error);
  }
};

// 处理图片上传成功的回调
const handleImageSuccess = (response, uploadFile) => {
  // 设置新头像 URL
  imageBasePath.value = URL.createObjectURL(uploadFile.raw!)
  // 更新作品封面
  console.log("response.upFile；" + response.upFile)
  work.value.wimage = response.upFile; // 假设后端返回的文件名
  console.log("work.wimage：" + work.value.wimage)
};

// 上传图片前的回调
const beforeImageUpload = (file) => {
  // 获取上传头像的后缀
  const fileSuffix = file.name.substring(file.name.lastIndexOf('.') + 1).toLowerCase()
  // const fileSuffix = file.name.split('.').pop().toLowerCase();
  const allowedTypes = ['png', 'jpg', 'jpeg', 'gif'];

  if (!allowedTypes.includes(fileSuffix)) {
    alert('只允许上传图片格式：png, jpg, jpeg, gif');
    return false;
  }

  if (file.size / 1024 / 1024 > 4) {
    alert('图片大小不能超过 4MB');
    return false;
  }

  return true;
};



// 提交修改后的剧本信息
const updateWork = async () => {

  try {
    console.log("修改数据：" + JSON.stringify(work.value, null, 2));
    const response = await axios.post('http://localhost:8080/api/updateworkByWrite', work.value); 
    // 根据需要处理响应
    console.log('Book updated successfully:', response.data);
  } catch (error) {
    console.error('Error updating book info:', error);
  }
};


const goToContractSettings = () => {
  router.push({ name: 'ContractSettings' }); // 跳转到合同设置页面
};

// 页面挂载后获取书籍信息
onMounted(async () => {
  const wid = route.params.id;
  await fetchBookInfo(wid);
  await fetchScriptTypes(wid); // 获取题材列表
});
</script>

<template>
  <div class="setting-container">
    <div class="sidebar">
      <el-menu default-active="1" mode="horizontal">
        <el-menu-item index="1">作品设置</el-menu-item>
        <el-menu-item index="2"  @click="goToContractSettings">合同设置</el-menu-item>
      </el-menu>
    </div>

    <div class="main-content">
      <div class="content-wrapper">
        <div class="cover-container">
          <h3 class="cover-title" style="margin: 15px 0px;">作品封面</h3>
          <el-upload class="upload-demo" action="http://localhost:8080/api/upload" :on-success="handleImageSuccess"
            :before-upload="beforeImageUpload" :show-file-list="false">
            <img :src="imageBasePath" alt="作品封面" class="book-cover" />
            <!-- <div class="el-upload__text">点击上传新封面</div> -->
          </el-upload>
        </div>

        <div class="info-container">
          <el-form label-width="130px" class="form">
            <el-form-item label="剧本名称">
              <el-input v-model="work.wname" placeholder="输入剧本名称"></el-input>
            </el-form-item>

            <el-form-item label="类型">
              <span>{{ work.typeID }}</span>
            </el-form-item>

            <el-form-item label="题材">
                <!-- <span v-for="scriptType in scriptTypes" :key="scriptType.bname">
                  {{ scriptType.bname}}
                </span> -->
                <span>
                  {{ scriptTypes.map(scriptType => scriptType.bname).join('、') }}
                </span>
            </el-form-item>

            <el-form-item label="剧本审核状态">
              <span>{{ work.workWstate }}</span>
            </el-form-item>

            <el-form-item label="版权登记号">
              <el-input v-model="work.copyright" placeholder="输入版权登记号"></el-input>
            </el-form-item>

            <el-form-item label="备案号">
              <el-input v-model="work.record" placeholder="输入备案号"></el-input>
            </el-form-item>

            <el-form-item label="作者意愿（金额）">
              <el-input v-model="work.money" placeholder="输入金额"></el-input>
            </el-form-item>

            <el-form-item label="剧本简介">
              <el-input type="textarea" v-model="work.introduction" placeholder="输入剧本简介"></el-input>
            </el-form-item>

            <el-form-item label="剧本状态">
              <span>{{ work.workScriptState }}</span>
            </el-form-item>

            <el-form-item label="征稿公告ID">
              <span>{{ work.zid }}</span>
            </el-form-item>

            <el-form-item label="编剧简介">
              <el-input type="textarea" v-model="work.screenwriterBio" placeholder="输入编剧简介"></el-input>
            </el-form-item>

            <el-form-item>
              <el-button type="primary" @click="updateWork">修改</el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.setting-container {
  background-color: #fef5e9;
  width: 100%;
  height: 100%;
  /* display: flex;
  padding: 16px; */
}

.sidebar {
  width: 100%;
  /* 更改为100%以充分利用空间 */
  margin-bottom: 2px;
  /* 添加下边距分隔内容 */
}

.main-content {
  height: 88.5%;
  flex: 1;
}

.content-wrapper {
  height: 100%;
  padding: 0px;
  display: flex;
}

.cover-container {
  margin-right: 20px;
  /* 设置封面与信息之间的间距 */
  width: 30%;
  height: 100%;
  text-align: center;
  /* 使内容居中对齐 */
}

.book-cover {
  width: 70%;
  height: 50%;
}

.info-container {
  flex: 1;
  /* 使信息部分充满剩余空间 */
  height: 100%;
}

.form {
  padding: 20px;
  border-radius: 4px;
  height: 95;
}

.info-container .el-form-item:nth-child(2),
.info-container .el-form-item:nth-child(3),
.info-container .el-form-item:nth-child(4) {
  margin-bottom: 5px; /* 减小“类型”、“题材”、“剧本审核状态”间隔 */
}
</style>